<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-4">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #link_default="{ row }">
          <el-link :href="row.link" target="_blank" type="primary"
            >{{ t("device_update.download") }}
            <span v-if="row.version_name">（v{{ row.version_name }}）</span>
          </el-link>
        </template>
        <template #use_test_default="{ row }">
          <el-tag :type="row.use_test ? 'success' : 'info'"
            >{{ row.use_test ? t("device_update.yes") : t("device_update.no") }}
          </el-tag>
        </template>
      </AuTable>
    </div>

    <UpdateModel v-model="showModel" :formData="rowData" @submit="search" />
  </div>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  onBeforeMount,
  onMounted,
  reactive,
  ref
} from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import {
  softwareUpgradeDel,
  softwareUpgradeGetList,
  SoftwareUpgradeListProps
} from "@/api/factory/device";
import UpdateModel from "@/views/factory/deviceMaintain/checkUpdate/UpdateModel.vue";
import { ElMessage } from "element-plus";
import { SEARCH_FORM_LIST } from "./constant";
import router from "@/router";
import { businessGetList } from "@/api/factory/business";
import { storageLocal } from "@pureadmin/utils";
import { userKey } from "@/utils/auth";
import { useI18n } from "vue-i18n";
import { setDeviceTypeTrans } from "@/utils/tool";
import { DEVICE_TYPE_TRANS } from "@/utils/constants";

defineOptions({
  name: "FactoryCheckUpdate"
});

// region 声明ref变量集合
const { t, te } = useI18n();
const { proxy } = getCurrentInstance();
const formList = ref(SEARCH_FORM_LIST);
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  columns: [
    {
      field: "id",
      title: "device_update.table.upgrade_id",
      width: 100,
      align: "center"
    },
    {
      field: "business_name",
      title: "device_update.table.business_name",
      minWidth: 120,
      align: "center"
    },
    {
      field: "device_type",
      title: "device_update.table.device_type",
      minWidth: 120,
      align: "center",
      formatter({ row }) {
        return te(DEVICE_TYPE_TRANS[row.device_type])
          ? t(DEVICE_TYPE_TRANS[row.device_type])
          : row.device_type;
      }
    },
    {
      field: "device_model",
      title: "device_update.table.device_model",
      minWidth: 160,
      align: "center"
    },
    {
      field: "version",
      title: "device_update.table.version",
      minWidth: 120,
      align: "center"
    },
    {
      field: "link",
      title: "device_update.table.upgrade_package",
      width: 150,
      slots: {
        default: "link_default"
      },
      align: "center"
    },
    {
      field: "size",
      title: "device_update.table.size",
      minWidth: 90,
      align: "center"
    },
    {
      field: "use_test",
      title: "device_update.table.is_test",
      minWidth: 100,
      align: "center",
      slots: {
        default: "use_test_default"
      }
    },
    {
      field: "content",
      title: "device_update.table.upgrade_content",
      minWidth: 180,
      align: "center"
    },
    // {
    //   field: "is_force",
    //   title: "强制升级",
    //   minWidth: 90,
    //   slots: {
    //     default: "isForce_default"
    //   },
    //   align: "center"
    // },
    {
      field: "update_time",
      title: "device_update.table.update_time",
      width: 170,
      align: "center"
    }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.EDIT, ACTION_TYPE.DELETE],
  topTools: [],
  operateTools: [
    {
      key: "record",
      name: "table.softwareRecord",
      plain: true,
      onClick: (row: SoftwareUpgradeListProps) => {
        toPage(row);
      }
    }
  ],
  dataSource: []
  // fetchConfig: {
  //   query: {
  //     service: (params: ObjectProps) => {
  //       return softwareUpgradeGetList(params);
  //     },
  //     param: () => formRef.value.getFormData()
  //   }
  // }
});
const showModel = ref(false);
const rowData = ref(null);
const formRef = ref();
const tableRef = ref();

const { post } = storageLocal().getItem<{
  post: number;
}>(userKey);

// endregion

// region 公共方法的集合
const businessSet = () => {
  businessGetList({ size: 0 }).then(res => {
    formRef.value.setFormProps("business_id", { options: res.data });
  });
};

const getUpdateList = async () => {
  const res = await softwareUpgradeGetList({
    size: 0,
    start_page: 1,
    ...formRef.value.getFormData()
  });
  // gridOption.dataSource = res.data;
  return res.data;
};
// endregion

// region 组件事件的集合
const search = () => {
  // tableRef.value.refresh();
  getUpdateList().then(list => {
    // 软件更新帐号只能显示非测试数据
    if (post == 63 || post == 94) {
      gridOption.dataSource = list.filter(item => item.use_test != 1);
    } else {
      gridOption.dataSource = list;
    }
  });
};

type ActionType = {
  key: ACTION_TYPE;
  row: SoftwareUpgradeListProps;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case ACTION_TYPE.TADD:
      rowData.value = null;
      showModel.value = true;
      break;
    case ACTION_TYPE.EDIT:
      rowData.value = row;
      showModel.value = true;
      break;
    case ACTION_TYPE.DELETE:
      proxy.$auMessageBox
        .confirm(t("device_update.delete_confirm", { id: row.id }))
        .then(() => {
          const params = {
            delList: JSON.stringify([row])
          };
          softwareUpgradeDel(params).then(res => {
            if (res.code === 200) {
              ElMessage.success(t("notice.delete_success"));
              search();
            }
          });
        });
      break;
  }
};

const toPage = (row: SoftwareUpgradeListProps) => {
  const { id } = row;
  router.push({
    name: "FactorySoftwareRecord",
    query: {
      id
    }
  });
};

// endregion
onMounted(() => {
  businessSet();

  if (post == 63 || post == 94) {
    gridOption.actions = [];
    // gridOption.operateTools = [];
    gridOption.columns = gridOption.columns.filter(
      item => item.field !== "use_test"
    );
  }
  search();
});
</script>
